﻿<%@ Page Language="C#" Inherits="System.Web.UI.Page" %>
<%@ Implements Interface="Cms.Application.ITranslatable" %>
<%@ Import Namespace="iLib.Web.UI" %>
<%@ Import Namespace="Cms.Application" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="Ionic.Zip" %>
<%@ Import Namespace="System.Net" %>
<%@ Import Namespace="System.Security" %>
<%@ Import Namespace="Cms.Utilities" %>
<script runat="server">

        #region ITranslatable Members

    public string ContextTranslationFile
    {
        get { return "Admin/Translations/Install.xml"; }
    }


    public string Localization
    {
        get { return (string) (ViewState["Localization"] ?? "en-US"); }
        set { ViewState["Localization"] = value; }
    }

        #endregion

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        Response.HeaderEncoding = Encoding.UTF8;
        Header.Controls.Add(new iLibRegistrator());
    }


    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);
        Title = Translator.GetText(ContextTranslationFile, "Title", Localization);
    }


    public void lbInstall_Click(object sender, EventArgs e)
    {
        Logging.LogInfo("Start installation");
        pnlStartInstallation.Visible = true;
        litStatus.Text = Translator.GetText(ContextTranslationFile, "llUnzipping", Localization);
        Page.ClientScript.RegisterStartupScript(GetType(), "start", "document.getElementById('btnUnzip').click();", true);
    }


    private string GetPath()
    {
        string path = Server.MapPath(Request.ApplicationPath);
        if (!path.EndsWith("\\"))
            path += "\\";
        return path;
    }


    public void btnUnzip_Click(object sender, EventArgs e)
    {
        Logging.LogInfo("Start unzipping");
        if (!File.Exists(GetPath() + "Fredium.zip"))
            return;
        using (ZipFile zip = ZipFile.Read(GetPath() + "Fredium.zip"))
        {
            zip.ExtractAll(GetPath(), ExtractExistingFileAction.OverwriteSilently);
        }
        Logging.LogInfo("Zip extracted");
        File.Delete(GetPath() + "Fredium.zip");
        Logging.LogInfo("Zip deleted");
        litStatus.Text = Translator.GetText(ContextTranslationFile, "llCompiling", Localization);
        Page.ClientScript.RegisterStartupScript(GetType(), "unzip", "document.getElementById('btnCompile').click();",
                                                true);
    }


    public void btnCompile_Click(object sender, EventArgs e)
    {
        Logging.LogInfo("Enter btnCompile_Click");
        if (ConfigurationManager.AppSettings["AspNetIsRestartedManually"] == "true")
        {
            pnlManualRestart.Visible = true;
            return;
        }
        if (!IsApplicationRunning())
        {
            System.Threading.Thread.Sleep(2000);
            Logging.LogInfo("Register new call to btnCompile_Click");
            Page.ClientScript.RegisterStartupScript(GetType(), "compile", "document.getElementById('btnCompile').click();", true);
        }
        else
        {
            Response.Redirect("ConfigureDatabase.aspx");
        }
    }


    private bool IsApplicationRunning()
    {
        Logging.LogInfo("Enter IsApplicationRunning");
        string url;
        HttpRequest request = HttpContext.Current.Request;
        int port = request.Url.Port;
        url = request.IsSecureConnection ? "https://" : "http://";
        url += request.Url.Host;
        if (port != 80 && port != 443)
        {
            url += ":" + port;
        }
        url += request.ApplicationPath;
        if (!url.EndsWith("/"))
        {
            url += "/";
        }
        url += "Install.aspx";
        var req = (HttpWebRequest) WebRequest.Create(url);
        req.Timeout = 4000;
        HttpWebResponse resp;
        bool result = false;
        try
        {
            resp = (HttpWebResponse) req.GetResponse();
            Logging.LogInfo("WebRequest response: " + resp.StatusCode);
            if (resp.StatusCode == HttpStatusCode.OK)
            {
                result = true;
            }
        }
        catch (WebException ex)
        {
            Logging.LogInfo("WebRequest failed: " + ex);
            if (ex.Status == WebExceptionStatus.ProtocolError)
            {
                resp = ex.Response as HttpWebResponse;
                if (resp != null)
                {
                    /*
                    StreamReader sr = new StreamReader(resp.GetResponseStream());
                    result = sr.ReadToEnd();
                    sr.Close();
                    sr.Dispose();
                    path = this.UserPhysicalTempDirectory + "ErrorDetails.aspx";
                    IO.DeleteFile(path);
                    IO.CreateTextFile(path, result);
                    result = result.Substring(result.IndexOf("<title>", StringComparison.InvariantCultureIgnoreCase) + 7);
                    result = result.Substring(0, result.IndexOf("</title>", StringComparison.InvariantCultureIgnoreCase));
                    */
                }
            }
        }
        return result;
    }


    private AspNetHostingPermissionLevel GetCurrentTrustLevel()
    {
        foreach (AspNetHostingPermissionLevel trustLevel in
            new[]
                {
                    AspNetHostingPermissionLevel.Unrestricted,
                    AspNetHostingPermissionLevel.High,
                    AspNetHostingPermissionLevel.Medium,
                    AspNetHostingPermissionLevel.Low,
                    AspNetHostingPermissionLevel.Minimal
                })
        {
            try
            {
                new AspNetHostingPermission(trustLevel).Demand();
            }
            catch (SecurityException)
            {
                continue;
            }

            return trustLevel;
        }
        return AspNetHostingPermissionLevel.None;
    }


    protected void lbLocalization_Click(object sender, EventArgs e)
    {
        string localization = (sender as LinkButton).CommandArgument;
        ViewState["Localization"] = localization;
        var cookie = new HttpCookie("FrediumAdminLocalization", localization);
        cookie.Expires = DateTime.Now.AddYears(1);
        Response.Cookies.Add(cookie);
    }


</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <link rel="stylesheet" type="text/css" href="Admin/Css/Main.css" />
    <link rel="stylesheet" type="text/css" href="Admin/Css/MainBox.css" />
    <link rel="stylesheet" type="text/css" href="Admin/Css/Public.css" />
    <link rel="stylesheet" type="text/css" href="Admin/Css/Buttons.css" />
    <link rel="stylesheet" type="text/css" href="Admin/Css/Dialogs.css" />
    <link rel="stylesheet" type="text/css" href="Admin/Css/PopupMenu.css" />
    <script language="javascript" type="text/javascript" src="Admin/Js/CmsLib.js"></script>
    <script language="javascript" type="text/javascript" src="Admin/Js/Dialogs.js"></script>
    <script language="javascript" type="text/javascript" src="Admin/Js/Lists.js"></script>
    <script language="javascript" type="text/javascript">
        //<![CDATA[
        function init() {
            cms.Dialogs.RenderAlerts();
            var selectLocalization = document.getElementById("selectLocalization");
            var mainBox = document.getElementById("mainBox");
            iLib.Dom.AddListener(selectLocalization, "click", function(e) {
                e = e || window.event;
                var target = e.target || e.srcElement;
                iLib.Dom.PreventBubble(e);
                cms.Lists.ShowPopup(document.getElementById("pnlLocales"), target, "right", iLib.Pos.FindX(mainBox) + 3, iLib.Pos.FindY(mainBox) + 2, true, e);
            });
        }

        try {
            if (!HTMLAnchorElement.prototype.click) {
                HTMLAnchorElement.prototype.click = function() {
                    var evt = document.createEvent('MouseEvents');
                    evt.initEvent('click', true, true);
                    if (this.dispatchEvent(evt) !== false)
                        document.location.href = this.href;
                }
            }
        }
        catch (err) {
        }
        //]]>
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true" EnablePageMethods="true">
        </asp:ScriptManager>
        <div id="publicContainer">
            <div id="ctl00_mainBoxTopOuterContainer">
                <div id="mainBoxTopInnerContainer">
                    <div id="mainBoxTop">
                        <div id="mainBoxTopBg">&nbsp;</div>
                        <div id="mainBoxTopLeftCorner">&nbsp;</div>
                        <div id="mainBoxTopRightCorner">&nbsp;</div>
                    </div>
                </div>
            </div>
            <div id="mainBox">
                <div id="mainBoxLeftBg">&nbsp;</div>
                <div id="mainBoxRightBg">&nbsp;</div>
                <div id="mainBoxContent">
                    <div id="padding">
                        <div class="floatLeft">
                            <img id="imgLogo" runat="server" src="~/Admin/Img/frediumLogo-dark.png" alt="Fredium" />
                        </div>
                        <div class="floatRight" style="padding-top: 2px;">
                            <a id="selectLocalization" href="javascript:void(0);"><cms:LocalizedLiteral ID="llSelectLocalization" runat="server" /></a>
                        </div>
                        <div class="clearFloats"></div>
                        <div style="margin-top: 10px;">
                            <h1><cms:LocalizedLiteral ID="llHeader" runat="server" /></h1>
                            <p>Press the Start installation button to unzip the application files and configure the system.</p>
                            <asp:panel id="pnlStartInstallation" runat="server" Visible="false">
                                <div class="horizontalDivider" style="margin-bottom: 10px; margin-top: 10px;"></div>
                                <p><strong><asp:literal ID="litStatus" runat="server" /></strong></p>
                            </asp:panel>
                            <div class="horizontalDivider" style="margin-bottom: 10px; margin-top: 10px;"></div>
                            <p>
                                <asp:LinkButton ID="lbInstall" runat="server" OnClick="lbInstall_Click" CssClass="orangeButton"><span><span><img src="Admin/Img/icons/application_start.png" alt="" /><span><cms:LocalizedLiteral ID="llInstall" runat="server" /></span></span></span></asp:LinkButton>
                            </p>
                            <asp:Panel ID="pnlManualRestart" runat="server" Visible="false">
                                <a href="ConfigureDatabase.aspx">Restart ASP.NET and click here to continue...</a>
                            </asp:Panel>
                            <div style="position: absolute; left: -10000px;">
                                <asp:Button ID="btnUnzip" runat="server" OnClick="btnUnzip_Click" Text="Unzip" />
                                <asp:Button ID="btnCompile" runat="server" OnClick="btnCompile_Click" Text="Compile" />
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div id="mainBoxBottom">
                <div id="mainBoxBottomBg">&nbsp;</div>
                <div id="mainBoxBottomLeftCorner">&nbsp;</div>
                <div id="mainBoxBottomRightCorner">&nbsp;</div>
            </div>
        </div>
        <asp:panel id="pnlLocales" runat="server" cssclass="popup">
            <div class="popupMenuTop">
                <div class="popupMenuTopBg">&nbsp;</div>
                <div class="popupMenuTopLeftCorner">&nbsp;</div>
                <div class="popupMenuTopRightCorner">&nbsp;</div>
            </div>
            <div class="popupMenu">
                <div class="popupMenuLeftBg">&nbsp;</div>
                <div class="popupMenuRightBg">&nbsp;</div>
                <div class="popupMenuContent">
                    <asp:LinkButton ID="lbEnglish" runat="server" OnClick="lbLocalization_Click" CommandArgument="en-US"><img id="imgUS" runat="server" src="~/Admin/Img/us.png" /><span>English</span></asp:LinkButton>
                    <asp:LinkButton ID="lbSwedish" runat="server" OnClick="lbLocalization_Click" CommandArgument="sv-SE"><img id="imgSweden" runat="server" src="~/Admin/Img/se.png" /><span>Svenska</span></asp:LinkButton>
                </div>
            </div>
            <div class="popupMenuBottom">
                <div class="popupMenuBottomBg">&nbsp;</div>
                <div class="popupMenuBottomLeftCorner">&nbsp;</div>
                <div class="popupMenuBottomRightCorner">&nbsp;</div>
            </div>
        </asp:panel>
    
    </form>
    <script language="javascript" type="text/javascript">
        //<![CDATA[
        iLib.Dom.AddListener(window, "load", init);
        //]]>
    </script>
</body>
</html>
